package com.xuerhua.yxt.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.enums.DictDataCode;
import com.xuerhua.yxt.common.enums.RelationType;
import com.xuerhua.yxt.common.enums.WorkApprovalStatus;
import com.xuerhua.yxt.common.enums.WorkApprovalType;
import com.xuerhua.yxt.dao.AttachmentListMapper;
import com.xuerhua.yxt.dao.SchoolWechatTemplateMapper;
import com.xuerhua.yxt.dao.TeacherInfoMapper;
import com.xuerhua.yxt.dao.WorkApprovalItemMapper;
import com.xuerhua.yxt.dao.WorkApprovalMapper;
import com.xuerhua.yxt.model.AttachmentList;
import com.xuerhua.yxt.model.SchoolInfo;
import com.xuerhua.yxt.model.TeacherInfo;
import com.xuerhua.yxt.model.WorkApproval;
import com.xuerhua.yxt.model.WorkApprovalItem;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.AttachRelationReqVO;
import com.xuerhua.yxt.reqVo.WorkApprovalCountQueryVO;
import com.xuerhua.yxt.reqVo.WorkApprovalReqVO;
import com.xuerhua.yxt.service.ISchoolInfoService;
import com.xuerhua.yxt.service.IWorkApprovalService;
import com.xuerhua.yxt.utils.BeanUtils;
import com.xuerhua.yxt.view.CopyPaperApprovalView;
import com.xuerhua.yxt.view.OvertimeApplyView;
import com.xuerhua.yxt.view.PrintingPaperApprovalView;
import com.xuerhua.yxt.view.SchoolBusApprovalView;
import com.xuerhua.yxt.view.WorkApprovalView;
import com.xuerhua.yxt.view.teachingGoodsApprovalView;
import com.xuerhua.yxt.wechat.utils.TemplateUtil;

@Service("workApprovalService")
public class WorkApprovalServiceImpl implements IWorkApprovalService {

	@Autowired
	private WorkApprovalMapper workApprovalMapper;
	@Autowired
	private WorkApprovalItemMapper workApprovalItemMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	@Autowired
	private ISchoolInfoService schoolInfoService;
	@Autowired
	private SchoolWechatTemplateMapper schoolWechatTemplateMapper;
	
	@Override
	public int addWorkApproval(WorkApprovalReqVO reqVO) {
		WorkApproval wa = BeanUtils.copyAs(reqVO, WorkApproval.class);
		wa.setApplyTime(new Date());
		workApprovalMapper.insertSelective(wa);
		WorkApprovalItem waItem = BeanUtils.copyAs(reqVO, WorkApprovalItem.class);
		waItem.setApplyId(wa.getId());
		if(reqVO.getAttachIds()!= null) {
			AttachRelationReqVO attachReqVO = new AttachRelationReqVO();
			attachReqVO.setRelationId(Long.valueOf(wa.getId()));
			attachReqVO.setAttachIds(reqVO.getAttachIds().split(","));
			attachmentListMapper.updateRelationIdByIds(attachReqVO);
			waItem.setIsAttach(1);
		}
		workApprovalItemMapper.insertSelective(waItem);
		new Thread(new WorkApprovalExecutor(wa, 1)).start();
		return 1;
	}

	@Override
	public WorkApproval selectByPrimaryKey(Integer id) {
		return workApprovalMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(WorkApproval record) {
		return workApprovalMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<WorkApprovalView> selectViewListByPage(Page<WorkApprovalView> page) {
		return workApprovalMapper.selectViewListByPage(page);
	}

	@Override
	public WorkApprovalView selectViewDetail(WorkApproval wa) {
		WorkApprovalView view = workApprovalMapper.selectViewDetail(wa);
		if (view.getItem().getIsAttach() == 1) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", RelationType.WORK_APPROVAL.getCode());
			map.put("objId", view.getItem().getId());
			List<AttachmentList> attachmentList = attachmentListMapper.queryAttachmentListByRelationId(map);
			view.setAttachList(attachmentList);
		}
		if(StringUtils.isNotBlank(view.getCcList())) {
			List<String> list = Arrays.asList(view.getCcList().split(","));
			List<TeacherInfo> teacherList = teacherInfoMapper.selectListByIds(list);
			view.setCcTeacherList(teacherList);
		}
		return view;
	}

	@Override
	public WorkApproval selectForApproval(WorkApprovalReqVO reqVO) {
		return workApprovalMapper.selectForApproval(reqVO);
	}

	@Override
	public boolean isApprover(Integer teacherId) {
		return workApprovalMapper.selectCountForApprover(teacherId) > 0 ? true : false;
	}
	
	@Override
	public int updateApproval(WorkApproval record) {
		workApprovalMapper.updateByPrimaryKeySelective(record);
		new Thread(new WorkApprovalExecutor(record, 2)).start();
		return 1;
	}
	
	class WorkApprovalExecutor implements Runnable {
		
		//1新增审批 2审批
		private int type;
		
		private WorkApproval record;
		
		public WorkApprovalExecutor(WorkApproval record, int type) {
			this.record = record;
			this.type = type;
		}

		@Override
		public void run() {
			try { 
				SchoolInfo school = schoolInfoService.queryInitWechatBySchoolId(record.getSchoolId());
				String reqUrl = school.getDomainUrl() + Const.TEACHER_ROLE + 
						MenuConst.WORK_APPROVAL + "/detail/" + record.getId();
				if(type == 1) {
					String templateId = schoolWechatTemplateMapper.selectTemplateKey(
							record.getSchoolId(), DictDataCode.WORK_APPROVAL_APPLY.getCode());
					TeacherInfo teacher = teacherInfoMapper.selectByPrimaryKey(record.getApproverId());
					String approvalType = WorkApprovalType.getDesc(record.getApprovalType());
					TemplateUtil.approvalApplySend(school,teacher.getOpenid(), approvalType, 
							record.getApplyer(), approvalType, record.getApplyTime(), templateId, reqUrl);
				}else {
					String templateId = schoolWechatTemplateMapper.selectTemplateKey(
							record.getSchoolId(), DictDataCode.WORK_APPROVAL_RESULT.getCode());
					WorkApproval approval = workApprovalMapper.selectByPrimaryKey(record.getId());
					String approvalType = WorkApprovalType.getDesc(approval.getApprovalType());
					String approvalResult = WorkApprovalStatus.getDesc(record.getApprovalStatus());
					TeacherInfo applyTeacher = teacherInfoMapper.selectByPrimaryKey(approval.getApplyerId());
					String title = "您好,你提交的申请已经审批";
					TemplateUtil.approvalResultSend(school,applyTeacher.getOpenid(), title, approvalType, 
							approvalResult, record.getApprovalTime(), templateId, reqUrl);
					if(StringUtils.isNotBlank(record.getCcList()) && 
						record.getApprovalStatus().equals(WorkApprovalStatus.AUDIT_SUCCESS.getCode())) {
						List<String> array = Arrays.asList(record.getCcList().split(","));
						List<TeacherInfo> list = teacherInfoMapper.selectListByIds(array);
						title = "您好，有一条审批通过的申请抄送给您，请注意查收";
						for(TeacherInfo teacher : list) {
							school = schoolInfoService.refreshInitWechat(school);
							TemplateUtil.approvalResultSend(school,teacher.getOpenid(), title, approvalType, 
									approvalResult, record.getApprovalTime(), templateId, reqUrl);
						}
					}
				}
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}

	@Override
	public int countAllRecord(WorkApprovalCountQueryVO vo) {
		return workApprovalMapper.countAllRecord(vo);
	}

	@Override
	public List<CopyPaperApprovalView> selectWorkApprovalOfCopyPaperByPage(Page<CopyPaperApprovalView> page) {
		return workApprovalMapper.selectWorkApprovalOfCopyPaperByPage(page);
	}

	
	@Override
	public List<PrintingPaperApprovalView> selectWorkApprovalOfPrintingPaperByPage(Page<PrintingPaperApprovalView> page) {
		return workApprovalMapper.selectWorkApprovalOfPrintingPaperByPage(page);
	}

	@Override
	public List<teachingGoodsApprovalView> selectWorkApprovalOfTeachingGoodsByPage(Page<teachingGoodsApprovalView> page) {
		return workApprovalMapper.selectWorkApprovalOfTeachingGoodsByPage(page);
	}

	@Override
	public List<SchoolBusApprovalView> selectWorkApprovalOfSchoolbusByPage(Page<SchoolBusApprovalView> page) {
		return workApprovalMapper.selectWorkApprovalOfSchoolbusByPage(page);
	}

	@Override
	public List<OvertimeApplyView> selectWorkApprovalOfOvertimeApplyByPage(Page<OvertimeApplyView> page) {
		return workApprovalMapper.selectWorkApprovalOfOvertimeApplyByPage(page);
	}
}
